/*
 * @Author: hongbin
 * @Date: 2022-11-20 14:38:38
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-24 21:15:27
 * @Description: 好友列表
 */
import { FC, Fragment, useCallback, useEffect, useState } from "react";
import styled, { css } from "styled-components";
import { get, post } from "../../../api";
import { useAuth } from "../../../context/AuthProvide";
import { UserInfo } from "../../../hook/useRegisterForm";
import NotificationBar from "../../../HUI/NotificationBar";
import { SocketManager } from "../../../socket";
import { fadeIn, flexCenter } from "../../../styled";
import { Close } from "../../Icon";
import Friends from "./Friends";
import Peg from "./Peg";
import useAddFriendHook from "./useAddFriendHook";

interface IProps {
    user: UserInfo;
}

/**
 * 好友列表组件
 */
const FriendsList: FC<IProps> = ({ user }) => {
    const { recordUserInformation } = useAuth();
    const addFriend = useAddFriendHook();
    const [openPlane, setOpenPlane] = useState(false);
    const [newsCount, setNewsCount] = useState(1);
    const [requestInfo, setRequestInfo] = useState({ open: false, message: "欢迎回来", other: "" });
    const [loading, setLoading] = useState(false);

    const haveRequestAddFriendListen = useCallback((applicant: { applicant: string; applicantName: string }) => {
        console.log("请求加你好友", applicant);
        setRequestInfo({
            open: true,
            message: `${applicant.applicantName}请求加你为好友`,
            other: applicant.applicant,
        });
    }, []);

    /**
     * 接受到好友申请通知
     */
    useEffect(() => {
        //有人申请加你好友
        SocketManager.listen("haveRequestAddFriend", haveRequestAddFriendListen);
        //你的好友申请被同意
        SocketManager.listen("agreeAddFriend", async ({ other, otherName, chatRecordId }) => {
            console.log(`${otherName}同意加你为好友🎉`);
            //数据库操作在socket 服务器中执行 将对方加入你的好友列表
            //本地user 信息添加
            const newInfo = {
                ...user,
                friendsList: [...user.friendsList, { date: Date.now(), friendId: other, chatRecordId }],
            };
            recordUserInformation(newInfo);
        });
        return () => {
            SocketManager.removeListen("haveRequestAddFriend", haveRequestAddFriendListen);
        };
    }, [haveRequestAddFriendListen, recordUserInformation, user]);

    useEffect(() => {
        setNewsCount(0);
        if (openPlane) {
            //设置socket标识 防止socket找不到目标
            SocketManager.emit("setSocketId", user._id);
        }
    }, [openPlane, user._id]);

    /**
     * 关闭通知条
     */
    const closeNotification = useCallback(() => {
        setRequestInfo((prev) => ({ ...prev, open: false }));
    }, []);

    /**
     * 确认加对方为好友
     */
    const confirmAddFriend = useCallback(() => {
        setLoading(true);
        addFriend(requestInfo.other, () => {
            setLoading(false);
            closeNotification();
        });
    }, [addFriend, closeNotification, requestInfo.other]);

    return (
        <Fragment>
            <Container open={openPlane}>
                <Friends open={openPlane} user={user} />
                <Title
                    onClick={() => {
                        setOpenPlane(!openPlane);
                    }}
                >
                    {openPlane ? <Close /> : "好友列表"}
                </Title>
                <Peg newsCount={newsCount} />
            </Container>
            <NotificationBar
                loading={loading}
                duration={3000}
                {...requestInfo}
                onClose={closeNotification}
                onConfirm={confirmAddFriend}
                style={{
                    top: "20%",
                    right: "1vmax",
                }}
            />
        </Fragment>
    );
};

export default FriendsList;

const Title = styled.span`
    width: 5vmax;
    height: 5vmax;
    font-size: 1.8vmax;
    ${flexCenter};
    text-align: center;
    font-weight: bold;
    color: #fffae5;
    position: absolute;
    bottom: 0;
    right: 0;
    transition: 0.3s ease;
    svg {
        width: 3vmax;
        height: 3vmax;
        fill: #51aa35;
    }
`;

const Container = styled.div<{ open: boolean }>`
    position: absolute;
    bottom: 4vmax;
    right: 1vmax;
    background: #17610c;
    cursor: default;
    width: 5vmax;
    height: 5vmax;
    border-radius: 1vmax;
    transition: 0.3s ease;
    z-index: 12;
    animation: ${fadeIn} 0.3s;
    overflow: hidden;
    box-shadow: ${(props) => props.theme.boxShadow};

    ${({ open }) =>
        open &&
        css`
            width: 20vw;
            height: 30vw;
            ${Title} {
                width: 3vmax;
                height: 3vmax;
                cursor: pointer;
                top: 0vmax;
                right: 0vmax;
            }
        `}
`;
